package top.someapp.dxf2dsvg;

import com.aspose.cad.imageoptions.svgoptionsparameters.FontStoringArgs;
import com.aspose.cad.imageoptions.svgoptionsparameters.ISvgResourceKeeperCallback;
import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.util.List;

/**
 * @author zwz
 * Created on 2020-04-25
 */
public class SvgCleaner implements ISvgResourceKeeperCallback, ElementHandler {
    private static final OutputFormat xmlFormat = OutputFormat.createPrettyPrint();
    private final OutputStream out;
    private String id;

    public SvgCleaner(OutputStream out) {
        this(out, null);
    }

    public SvgCleaner(OutputStream out, String id) {
        this.out = out;
        this.id = id;
        xmlFormat.setIndent("\t");
        xmlFormat.setLineSeparator("\r\n");
        xmlFormat.setPadText(false);
    }

    @Override
    public String onImageResourceReady(byte[] bytes, int i, String s, boolean[] booleans) {
        return s;
    }

    @Override
    public void onFontResourceReady(FontStoringArgs fontStoringArgs) {

    }

    @Override
    public String onSvgDocumentReady(byte[] bytes, String s) {
        StringWriter stringWriter = new StringWriter();
        try (InputStream ins = new ByteArrayInputStream(bytes)) {
            Document document = cleanUpSvg(ins);
            XMLWriter xmlwriter = new XMLWriter(stringWriter, xmlFormat);
            xmlwriter.write(document);
            out.write(stringWriter.toString().getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "<svg/>";
    }

    private Document cleanUpSvg(InputStream ins) throws DocumentException {
        SAXReader reader = new SAXReader(/*true*/);
        // unwrap <g>
        Document document = reader.read(ins);
        Element root = document.getRootElement();
        if (root.hasContent()) {
            List<Element> groups = root.elements("g");
            if (!groups.isEmpty()) {
                root.remove(groups.get(groups.size() - 1));
            }
        }
        root.addComment(" Export by dxf2dsvg (https://gitee.com/zelde/dxf2dsvg) ");
        if (id != null) {
            root.addAttribute("id", id);
        }
        return document;
    }

    @Override
    public void onStart(ElementPath elementPath) {
    }

    @Override
    public void onEnd(ElementPath elementPath) {
        System.out.println(elementPath.getPath() + " END.");
        Element current = elementPath.getCurrent();
        System.out.println("attribute.size=" + current.attributeCount() + ", elements.size=" + current.elements().size());
        if (!current.hasContent()) {
            System.out.println("Found empty <g/>");
        } else if (current.attributeCount() == 0) {
            System.out.println("Found empty attribute <g/>");
        }
    }
}
